package com.benyi.util;

import java.util.HashMap;
import java.util.Map;

public class SimpleLanguageDetector {
    
	private static final String UNKNOWN = "unknown"; //unknown
	private static final String CODE_CHINA_SIMPLE = "china-simple";
	private static final String CODE_CHINA_FAN = "china-fan";
	private static final String CODE_JAPAN_CHINA = "japan-china";
	private static final String CODE_KORI = "kori";
	private static final String CODE_JAPAN_JIA = "japan-jia";
	private static final String CODE_RUSSIA = "russia";
	private static final String CODE_ARAB = "arab";
	private static final String CODE_THAILAND = "thailand";
	private static final String CODE_HEBOLAI = "hebolai";
	private static final String CODE_YINDI = "yindi";
	private static final String CODE_XILA = "greece";
	private static final String CODE_JAPAN = "japan";
	
	private static final String CODE_YUENAN = "vitnamese";
	private static final String CODE_YUENAN_STYLE = "vitnamese-style";
	
	private static final String CODE_ENGLISH = "english";
	private static final String CODE_FRENCH = "french";
	private static final String CODE_SPAIN = "spain";
	private static final String CODE_GERMANY = "germany";
	private static final String CODE_PORTUGAL = "portugal";
	private static final String CODE_ITALY = "italy"; 
	private static final String CODE_MIXED = "code-mixed";
	
    private static final Map<String, String> LANGUAGE_PATTERNS = new HashMap<>();
    private static final Map<String, String> LANGUAGE_NAMES = new HashMap<>();
    private static final Map<String, Integer> LANGUAGE_PRIORITY = new HashMap<>();
    
    static {
        // 语言字符范围模式（按优先级排序）
    	LANGUAGE_PATTERNS.put(CODE_CHINA_SIMPLE, "[\\u4e00-\\u9fa5]");        // 简体中文
        LANGUAGE_PATTERNS.put(CODE_CHINA_FAN, "[\\u4e00-\\u9fff]");        // 繁体中文
        LANGUAGE_PATTERNS.put(CODE_JAPAN_CHINA, "[\\u4e00-\\u9faf]");       // 日文汉字（与中文重叠）
        
        LANGUAGE_PATTERNS.put(CODE_KORI, "[\\uac00-\\ud7af]");             // 韩文（独有字符）
        LANGUAGE_PATTERNS.put(CODE_JAPAN_JIA, "[\\u3040-\\u309f\\u30a0-\\u30ff]");  // 日文假名（独有字符）
        
        LANGUAGE_PATTERNS.put(CODE_RUSSIA, "[\\u0400-\\u04ff]");             // 俄文
        LANGUAGE_PATTERNS.put(CODE_ARAB, "[\\u0600-\\u06ff]");             // 阿拉伯文
        LANGUAGE_PATTERNS.put(CODE_THAILAND, "[\\u0e00-\\u0e7f]");             // 泰文
        LANGUAGE_PATTERNS.put(CODE_HEBOLAI, "[\\u0590-\\u05ff]");             // 希伯来文
        LANGUAGE_PATTERNS.put(CODE_YINDI, "[\\u0900-\\u097f]");             // 印地文
        LANGUAGE_PATTERNS.put(CODE_XILA, "[\\u0370-\\u03ff]");             // 希腊文
        // 越南语特殊字符模式（声调符号和特殊字母）
        LANGUAGE_PATTERNS.put(CODE_YUENAN_STYLE, "[\\u0103\\u0102\\u0111\\u0110\\u01a1\\u01a0\\u01b0\\u01af[áàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵ]]");
        
        // 语言名称映射
        LANGUAGE_NAMES.put(CODE_CHINA_SIMPLE, "简体中文");
        LANGUAGE_NAMES.put(CODE_CHINA_FAN, "繁体中文");
        LANGUAGE_NAMES.put(CODE_JAPAN, "日文");
        LANGUAGE_NAMES.put(CODE_KORI, "朝鲜文");
        LANGUAGE_NAMES.put(CODE_ENGLISH, "英文");
        LANGUAGE_NAMES.put(CODE_FRENCH, "法文");
        LANGUAGE_NAMES.put(CODE_SPAIN, "西班牙文");
        LANGUAGE_NAMES.put(CODE_GERMANY, "德文");
        LANGUAGE_NAMES.put(CODE_RUSSIA, "俄文");
        LANGUAGE_NAMES.put(CODE_ARAB, "阿拉伯文");
        LANGUAGE_NAMES.put(CODE_PORTUGAL, "葡萄牙文");
        LANGUAGE_NAMES.put(CODE_ITALY, "意大利文");
        LANGUAGE_NAMES.put(CODE_YUENAN, "越南文");
        LANGUAGE_NAMES.put(CODE_THAILAND, "泰文");
        LANGUAGE_NAMES.put(CODE_YINDI, "印地文");
        LANGUAGE_NAMES.put(CODE_HEBOLAI, "希伯来文");
        LANGUAGE_NAMES.put(CODE_XILA, "希腊文");
        LANGUAGE_NAMES.put(CODE_MIXED, "混合语言");
        LANGUAGE_NAMES.put(UNKNOWN, "未知语言");
        
        // 语言检测优先级（数值越小优先级越高）
        LANGUAGE_PRIORITY.put(CODE_KORI, 1);
        LANGUAGE_PRIORITY.put(CODE_JAPAN_JIA, 2);
        LANGUAGE_PRIORITY.put(CODE_YUENAN_STYLE, 3); // 越南语优先级较高
        LANGUAGE_PRIORITY.put(CODE_CHINA_SIMPLE, 4);
        LANGUAGE_PRIORITY.put(CODE_CHINA_FAN, 5);
        LANGUAGE_PRIORITY.put(CODE_JAPAN_CHINA, 6); // 汉字优先级最低
        LANGUAGE_PRIORITY.put(CODE_RUSSIA, 7);
        LANGUAGE_PRIORITY.put(CODE_ARAB, 8);
        LANGUAGE_PRIORITY.put(CODE_THAILAND, 9);
        LANGUAGE_PRIORITY.put(CODE_HEBOLAI, 10);
        LANGUAGE_PRIORITY.put(CODE_YINDI, 11);
        LANGUAGE_PRIORITY.put(CODE_XILA, 12);
    }
    
    /**
     * 检测文本语言（修复版本）
     */
    public static String detectLanguageName(String text) {
        if (text == null || text.trim().isEmpty()) { 
            return UNKNOWN;
        }
        
        // 首先检查越南语（因为越南语使用拉丁字母但包含特殊字符）
        String vietnameseCheck = detectVietnamese(text);
        if (!vietnameseCheck.equals("unknown")) { 
            return vietnameseCheck;
        }
        
        // 统计各种语言字符的出现次数
        Map<String, Integer> languageScores = new HashMap<>();
        
        for (Map.Entry<String, String> entry : LANGUAGE_PATTERNS.entrySet()) {
            int count = countMatches(text, entry.getValue());
            if (count > 0) {
                languageScores.put(entry.getKey(), count);
            }
        }
        
        // 特殊处理：中文和日文的区分
        String detectedLang = distinguishChineseJapaneseCode(text, languageScores);
        if (!detectedLang.equals(UNKNOWN)) { 
        	return LANGUAGE_NAMES.get(detectedLang);
           // return detectedLang;
        }
        
        // 如果没有匹配到特定字符模式，判断为英文或其他拉丁语系
        if (languageScores.isEmpty()) {
            String code = detectLatinBasedLanguageCode(text);
            if(code.equals(UNKNOWN)) {
            	return UNKNOWN;
            }
            return LANGUAGE_NAMES.get(code);
        }
        
        // 根据优先级选择最可能的语言
        String code = selectLanguageByPriorityCode(languageScores);
        return LANGUAGE_NAMES.get(code);
    }
    
    public static String getLanguageName(String code) {
    	String name =  LANGUAGE_NAMES.get(code);
    	if(name == null) {
    		return UNKNOWN;
    	}
    	return name;
    }
    
    public static String detectLanguageCode(String text) {
        if (text == null || text.trim().isEmpty()) { 
            return UNKNOWN;
        }
        
        // 首先检查越南语（因为越南语使用拉丁字母但包含特殊字符）
        String vCode = detectVietnameseCode(text);
        if (!vCode.equals(UNKNOWN)) { 
            return vCode;
        }
        
        // 统计各种语言字符的出现次数
        Map<String, Integer> languageScores = new HashMap<>();
        
        for (Map.Entry<String, String> entry : LANGUAGE_PATTERNS.entrySet()) {
            int count = countMatches(text, entry.getValue());
            if (count > 0) {
                languageScores.put(entry.getKey(), count);
            }
        }
        
        // 特殊处理：中文和日文的区分
        String detectedLang = distinguishChineseJapaneseCode(text, languageScores);
        if (!detectedLang.equals("unknown")) { 
            return detectedLang;
        }
        
        // 如果没有匹配到特定字符模式，判断为英文或其他拉丁语系
        if (languageScores.isEmpty()) {
            return detectLatinBasedLanguageCode(text);
        }
        
        // 根据优先级选择最可能的语言
        return selectLanguageByPriorityCode(languageScores);
    }
    
    /**
     * 专门检测越南语
     */
    private static String detectVietnamese(String text) {
    	String code = detectVietnameseCode(text);
    	if(code.equals(UNKNOWN)) {
    		return UNKNOWN;
    	}
    	String name = LANGUAGE_NAMES.get(code);
    	if(name == null) {
    		return UNKNOWN;
    	}
    	return name; 
    }
    
    private static String detectVietnameseCode(String text) {
        // 越南语特有的字母和声调符号
        String vietnameseChars = "ăâđêôơưĂÂĐÊÔƠƯ";
        String vietnameseTones = "áàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựýỳỷỹỵ";
        
        int vietnameseCharCount = 0;
        int toneCount = 0;
        
        for (char c : text.toCharArray()) {
            if (vietnameseChars.indexOf(c) >= 0) {
                vietnameseCharCount++;
            }
            if (vietnameseTones.indexOf(c) >= 0) {
                toneCount++;
            }
        }
        
        // 越南语特征词
        String[] vietnameseWords = {
            "của", "là", "và", "trong", "được", "có", "cho", "với", "tôi", "bạn",
            "này", "khi", "từ", "như", "phải", "lên", "sau", "trước", "nếu", "thì",
            "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín", "mười",
            "người", "nhà", "nước", "thời", "công", "việc", "đời", "con", "gì", "ấy"
        };
        
        int wordMatchCount = 0;
        String cleanText = text.toLowerCase().replaceAll("[^a-zàáâãèéêìíòóôõùúýỳỹỷửữựừứợỡởờớộỗổồốọõỏòịĩỉìẹẽẻèệễểềếặẵẳằắạãảà\\s]", "");
        String[] words = cleanText.split("\\s+");
        
        for (String word : words) {
            if (word.length() < 2) continue;
            for (String viWord : vietnameseWords) {
                if (word.equals(viWord)) {
                    wordMatchCount++;
                    break;
                }
            }
        }
        
        // 越南语判断逻辑
        boolean hasVietnameseChars = vietnameseCharCount > 0;
        boolean hasTones = toneCount > 0;
        //boolean hasVietnameseWords = wordMatchCount > 0;
        
        // 如果有越南语特有字符，直接判断为越南语
        if (hasVietnameseChars && hasTones) { 
            //return LANGUAGE_NAMES.get(CODE_YUENAN);
        	return CODE_YUENAN;
        }
        
        // 如果有较多声调符号和越南语单词
        if ((toneCount >= 2 && wordMatchCount >= 2) || (vietnameseCharCount > 0 && toneCount > 0)) { 
            //return LANGUAGE_NAMES.get(CODE_YUENAN);
        	return CODE_YUENAN;
        }
        
        // 如果只有声调符号，需要进一步分析（可能与其他拉丁语系语言混淆）
        if (toneCount > 0) {
            // 检查是否包含其他语言的典型特征
            if (!hasOtherLatinLanguageFeatures(text)) { 
                return CODE_YUENAN;
            }
        } 
        return "unknown";
    }
    
    /**
     * 检查是否包含其他拉丁语系语言的典型特征
     */
    private static boolean hasOtherLatinLanguageFeatures(String text) {
        String lowerText = text.toLowerCase();
        
        // 检查德语特征
        if (lowerText.matches(".*[äöüß].*")) return true;
        
        // 检查法语特征
        if (lowerText.matches(".*[àâçéèêëîïôùûüÿœæ].*") && 
            !lowerText.matches(".*[ăâđêôơư].*")) { // 排除越南语字符
            return true;
        }
        
        // 检查西班牙语特征
        if (lowerText.matches(".*[áéíóúñ¿¡].*") && 
            !lowerText.matches(".*[àâđêôơư].*")) { // 排除越南语字符
            return true;
        }
        
        // 检查葡萄牙语特征
        if (lowerText.matches(".*[áâãàçéêíóôõú].*") && 
            !lowerText.matches(".*[ăâđêôơư].*")) { // 排除越南语字符
            return true;
        }
        
        return false;
    }
    
    /**
     * 区分中文和日文
     */
    private static String distinguishChineseJapaneseCode(String text, Map<String, Integer> languageScores) {
        boolean hasChineseChars = languageScores.containsKey(CODE_CHINA_SIMPLE) || languageScores.containsKey(CODE_CHINA_FAN);
        boolean hasJapaneseKana = languageScores.containsKey(CODE_JAPAN_JIA);
        boolean hasJapaneseKanji = languageScores.containsKey(CODE_JAPAN_CHINA);
        
        // 如果有日文假名，优先判断为日文
        if (hasJapaneseKana) { 
            //return LANGUAGE_NAMES.get(CODE_JAPAN);
        	return CODE_JAPAN;
        }
        
        // 如果只有汉字，使用更精确的区分方法
        if (hasChineseChars && !hasJapaneseKana) {
            return distinguishChineseTypeCode(text);
        }
        
        // 如果只有日文汉字（没有假名），很可能是中文
        if (hasJapaneseKanji && !hasJapaneseKana) {
            return distinguishChineseTypeCode(text);
        } 
        return UNKNOWN;
    }
    
    /**
     * 区分简体中文和繁体中文
     */
    private static String distinguishChineseTypeCode(String text ){
        int simplifiedCount = 0;
        int traditionalCount = 0;
        
        // 简体字特征字符（在繁体中文中不常用或写法不同）
        String[] simplifiedChars = {
            "这", "个", "们", "说", "话", "认", "识", "车", "东", "刘",
            "会", "体", "国", "过", "还", "时", "机", "发", "现", "电",
            "应", "还", "样", "点", "种", "见", "几", "从", "经", "样"
        };
        
        // 繁体字特征字符（在简体中文中不常用或写法不同）
        String[] traditionalChars = {
            "這", "個", "們", "說", "話", "認", "識", "車", "東", "劉",
            "會", "體", "國", "過", "還", "時", "機", "發", "現", "電",
            "應", "還", "樣", "點", "種", "見", "幾", "從", "經", "樣"
        };
        
        // 统计特征字符
        for (char c : text.toCharArray()) {
            String charStr = String.valueOf(c);
            for (String simplified : simplifiedChars) {
                if (simplified.equals(charStr)) {
                    simplifiedCount++;
                    break;
                }
            }
            for (String traditional : traditionalChars) {
                if (traditional.equals(charStr)) {
                    traditionalCount++;
                    break;
                }
            }
        }
        
        // 判断逻辑
        if (simplifiedCount > 0 && traditionalCount == 0) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_SIMPLE);
        	return CODE_CHINA_SIMPLE;
        } else if (traditionalCount > 0 && simplifiedCount == 0) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_FAN);
        	return CODE_CHINA_FAN;
        } else if (simplifiedCount > traditionalCount * 2) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_SIMPLE);
        	return CODE_CHINA_SIMPLE;
        } else if (traditionalCount > simplifiedCount * 2) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_FAN);
        	return CODE_CHINA_FAN;
        } else {
            // 难以区分时，根据整体字符倾向判断
            return detectChineseByCharacterFrequencyCode(text);
        }
    }
    
    /**
     * 通过字符频率判断中文类型
     */
    private static String detectChineseByCharacterFrequencyCode(String text) {
        // 常见简体字频率高于繁体字的情况
        int simpleFavored = 0;
        int tradFavored = 0;
        
        // 简繁对应字符对
        String[][] charPairs = {
            {"这", "這"}, {"个", "個"}, {"们", "們"}, {"说", "說"}, {"话", "話"},
            {"认", "認"}, {"识", "識"}, {"车", "車"}, {"东", "東"}, {"刘", "劉"},
            {"会", "會"}, {"体", "體"}, {"国", "國"}, {"过", "過"}, {"还", "還"}
        };
        
        for (String[] pair : charPairs) {
            int simpleCount = countMatches(text, pair[0]);
            int tradCount = countMatches(text, pair[1]);
            
            if (simpleCount > tradCount) simpleFavored++;
            if (tradCount > simpleCount) tradFavored++;
        }
        
        if (simpleFavored > tradFavored) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_SIMPLE);
        	return CODE_CHINA_SIMPLE;
        } else if (tradFavored > simpleFavored) { 
            //return LANGUAGE_NAMES.get(CODE_CHINA_FAN);
        	return CODE_CHINA_FAN;
        } else {
            // 默认判断为简体中文（因为简体更常见） 
            //return LANGUAGE_NAMES.get(CODE_CHINA_SIMPLE);
            return CODE_CHINA_SIMPLE;
        }
    }
    
    /**
     * 根据优先级选择语言
     */
    private static String selectLanguageByPriorityCode(Map<String, Integer> languageScores ){
        String bestLanguage = "unknown";
        int highestPriority = Integer.MAX_VALUE; 
        for (String langCode : languageScores.keySet()) {
            int priority = LANGUAGE_PRIORITY.getOrDefault(langCode, 100);
            if (priority < highestPriority) {
                highestPriority = priority;
                bestLanguage = langCode;
            }
        }
         
        // 处理语言代码映射
        if (bestLanguage.startsWith("zh-")) { 
            //return bestLanguage.equals(CODE_CHINA_SIMPLE) ? "简体中文" : "繁体中文";
        	return bestLanguage.equals(CODE_CHINA_SIMPLE) ? CODE_CHINA_SIMPLE : CODE_CHINA_FAN; 
        } else if (bestLanguage.startsWith("ja-")) {
            //return "日文";
        	return CODE_JAPAN;
        } else if (bestLanguage.equals(CODE_YUENAN_STYLE)) {
            //return "越南文";
        	return CODE_YUENAN;
        } else {
            //return LANGUAGE_NAMES.getOrDefault(bestLanguage, bestLanguage);
        	return bestLanguage;
        }
    }
    
    /**
     * 检测拉丁语系语言（修改版，排除越南语）
     */
    private static String detectLatinBasedLanguageCode(String text ){
        // 先检查越南语（二次确认）
        String vietnameseCheck = quickVietnameseCheck(text);
        if (vietnameseCheck.equals(CODE_YUENAN)) { 
           // return LANGUAGE_NAMES.get(CODE_YUENAN);
        	return CODE_YUENAN;
        }
        
        String cleanText = text.replaceAll("[^a-zA-Z\\s]", "").toLowerCase().trim();
        
        if (cleanText.isEmpty()) { 
            //return LANGUAGE_NAMES.get("unknown");
        	return UNKNOWN;
        }
        
        // 常见单词频率分析
        Map<String, Integer> wordScores = new HashMap<>();
        
        String[] englishWords = {"the", "and", "is", "in", "to", "of", "a", "that", "it", "for"};
        String[] frenchWords = {"le", "la", "et", "est", "en", "des", "un", "une", "que", "dans"};
        String[] spanishWords = {"el", "la", "y", "en", "ge", "que", "sp", "un", "una", "por"};
        String[] germanWords = {"der", "die", "und", "in", "den", "von", "zu", "das", "mit", "sich"};
        String[] vietnameseWords = {"của", "là", "và", "trong", "được", "có", "cho", "với", "tôi", "bạn"};
        
        String[] words = cleanText.split("\\s+");
        
        for (String word : words) {
            if (word.length() < 2) continue;
            
            for (String enWord : englishWords) {
                if (word.equals(enWord)) { 
                	wordScores.put(CODE_ENGLISH, wordScores.getOrDefault(CODE_ENGLISH, 0) + 1);
                }
            }
            for (String frWord : frenchWords) {
                if (word.equals(frWord)) { 
                	wordScores.put(CODE_FRENCH, wordScores.getOrDefault(CODE_FRENCH, 0) + 1);
                }
            }
            for (String esWord : spanishWords) {
                if (word.equals(esWord)) { 
                	wordScores.put(CODE_SPAIN, wordScores.getOrDefault(CODE_SPAIN, 0) + 1);
                }
            }
            for (String deWord : germanWords) {
                if (word.equals(deWord)) { 
                	wordScores.put(CODE_GERMANY, wordScores.getOrDefault(CODE_GERMANY, 0) + 1);
                }
            }
            for (String viWord : vietnameseWords) {
                if (word.equals(viWord)) { 
                	wordScores.put(CODE_YUENAN, wordScores.getOrDefault(CODE_YUENAN, 0) + 1);
                }
            }
        }
        
        if (!wordScores.isEmpty()) {
            String bestLang = wordScores.entrySet().stream()
                    .max(Map.Entry.comparingByValue())
                    .get()
                    .getKey(); 
            //return LANGUAGE_NAMES.getOrDefault(bestLang, bestLang);
            return bestLang;
        }
        
        // 特殊字符检测
        if (text.matches(".*[äöüß].*")) { 
        	//return "德文";
        	return CODE_GERMANY;
        }
        if (text.matches(".*[àâçéèêëîïôùûüÿœæ].*") && !text.matches(".*[ăâđêôơư].*")) { 
        	//return "法文";
        	return CODE_FRENCH;
        }
        if (text.matches(".*[áéíóúñ¿¡].*") && !text.matches(".*[ăâđêôơư].*")) { 
        	//return "西班牙文";
        	return CODE_SPAIN;
        } 
        //return "英文";
        return CODE_ENGLISH;
    }
    
    /**
     * 快速越南语检查
     */
    private static String quickVietnameseCheck(String text) {
        // 检查越南语特有字符
        if (text.matches(".*[ăâđêôơưĂÂĐÊÔƠƯ].*")) {
            return CODE_YUENAN;
        }
        
        // 检查越南语声调模式
        if (text.matches(".*[áàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựýỳỷỹỵ].*")) {
            // 排除其他语言的类似字符
            if (!text.matches(".*[äöüßàâçéèêëîïôùûüÿáéíóúñ].*")) {
                return CODE_YUENAN;
            }
        }
        
        return UNKNOWN;
    }
    
    /**
     * 统计匹配次数
     */
    private static int countMatches(String text, String pattern) {
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.substring(i, i + 1).matches(pattern)) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 获取检测详情
     */
    public static void printDetectionDetails(String text) {
        System.out.println("文本: " + text); 
        String code = detectLanguageCode(text);
        //detectLanguageName(text)
        System.out.println("检测结果: " + code +","+getLanguageName(code));
        
        // 显示字符统计
        Map<String, Integer> stats = new HashMap<>();
        for (char c : text.toCharArray()) {
            if (c >= '\u4e00' && c <= '\u9fff') {
                stats.put("中文汉字", stats.getOrDefault("中文汉字", 0) + 1);
            } else if (c >= '\u3040' && c <= '\u309f') {
                stats.put("日文平假名", stats.getOrDefault("日文平假名", 0) + 1);
            } else if (c >= '\u30a0' && c <= '\u30ff') {
                stats.put("日文片假名", stats.getOrDefault("日文片假名", 0) + 1);
            } else if (c >= '\uac00' && c <= '\ud7af') {
                stats.put("韩文", stats.getOrDefault("韩文", 0) + 1);
            } else if (Character.isLetter(c)) {
                if ("ăâđêôơưĂÂĐÊÔƠưáàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựýỳỷỹỵ".indexOf(c) >= 0) {
                    stats.put("越南文字母", stats.getOrDefault("越南文字母", 0) + 1);
                } else {
                    stats.put("拉丁字母", stats.getOrDefault("拉丁字母", 0) + 1);
                }
            }
        }
        System.out.println("字符统计: " + stats);
        System.out.println("---");
    }
    
    public static void main(String[] args) {
        // 测试用例
        String[] testTexts = {
            "你好，世界！这是简体中文",
            "你好，世界！這是繁體中文",
            "こんにちは。これは日本語です。", // 日文（包含假名）
            "今日は良い天気です。", // 日文（汉字+假名）
            "안녕하세요. 이것은 한국어입니다.", // 韩文
            "Hello, World! This is English text.",
            "Bonjour le monde. Ceci est du français.",
            "这是一个只包含汉字的文本", // 纯中文汉字
            "汉字のみのテキスト", // 日文汉字（无假名）
            "簡体字和繁體字混合使用", // 简繁混合
            "中文和English混合文本", // 中英混合
            "اَلْاجْتِهَادُ هُوَ مِفْتَاحُ النَّجَاحِ. بِالْعَمَلِ الدَّؤُوبِ وَالصَّبْرِ، تَتَحَقَّقُ الأَحْلَامُ وَتُقْهَرُ الصُّعُوبَاتُ. لَا يَصِلُ إِلَى قِمَّةِ الْجَبَلِ إِلَّا مَنْ يُصْعِدُ خُطًى ثَابِتَةً",
            // 越南语测试用例
            "Xin chào, đây là tiếng Việt", // 基本越南语
            "Hồ Hoàn Kiếm như một lẵng hoa giữa lòng thành phố", // 原测试用例
            "Việt Nam là một quốc gia xinh đẹp", // 越南语
            "Tôi yêu tiếng Việt", // 短句
            "Người dân Hà Nội rất thân thiện", // 包含声调
            "Ăn cơm với cá kho tộ", // 包含特殊字符
            "Đường phố Sài Gòn nhộn nhịp", // 越南地名
        };
        
        System.out.println("=== 修复后的语言检测测试（包含越南语）===\n");
        
        for (String text : testTexts) {
            printDetectionDetails(text);
        }
        
        // 专门测试越南语检测
        System.out.println("=== 越南语检测专项测试 ===");
        String[] vietnameseTests = {
            "Xin chào",
            "Cảm ơn bạn",
            "Tôi là người Việt Nam",
            "Hà Nội là thủ đô của Việt Nam",
            "Tiếng Việt có nhiều thanh điệu",
            "Ăn uống đầy đủ",
            "Đi du lịch khắp nơi"
        }; 
        for (String text : vietnameseTests) {
            System.out.println(text + " → " + detectLanguageName(text));
        }
    }
}